package com.azhuo.core.web.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.azhuo.core.pojo.User;
import com.azhuo.core.service.UserService;

@Controller
public class UserController {

	@Autowired
	private UserService userService;

	/**
	 * 用户登录 
	 */
	@RequestMapping(value = "/login.action", method=RequestMethod.POST)
	public String login(String usercode, String password, Model model, HttpSession session) {

		// 通过账号和密码查询用户
		User user = userService.findUser(usercode, password);

		if (user != null) {
			// 将登陆的用户保存到session中
			session.setAttribute("USER_SESSION", user);
			return "main";
		}

		model.addAttribute("msg", "账号或密码错误，请重新输入");
		return "login";
	}
	
	/**
	 * 用户注销 
	 */
	@RequestMapping(value="/logout.action")
	public String logout(HttpServletRequest request){
		request.setAttribute("msg", "用户已经退出");
		// 清除Session
		request.getSession().invalidate();
		// 重定向到登录界面
		return "login";
	}
	
	/**
	 * 去注册页面
	 */
	@RequestMapping(value="/toLogin.action", method=RequestMethod.GET)
	public String toLogin(){
		return "login";
	}
	
	/**
	 * 去注册页面
	 */
	@RequestMapping(value="/toRegist.action", method=RequestMethod.GET)
	public String toRegist(){
		return "regist";
	}
	
	/**
	 * 用户注册
	 */
	@RequestMapping(value="/regist.action", method=RequestMethod.POST)
	public String regist(String usercode, String password, Model model){
		userService.regist(usercode, password);
		model.addAttribute("msg", "注册成功，可以登录了。");
		return "login";
	}
	
	/**
	 * 去主页
	 */
	@RequestMapping(value="/toMain.action", method=RequestMethod.GET)
	public String toMain(){
		return "main";
	}
	
}
